package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.entity.Policy;
import com.xxx.entity.query.PolicyQuery;
import com.xxx.service.IPolicyService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xxx
 * @since 2024-11-24
 */
@RestController
@RequestMapping("/policy")
@Tag(name = "新闻政策管理")
public class PolicyController {
    @Autowired
    private IPolicyService policyService;

    @PostMapping("/add")
    @Operation(summary = "添加新闻政策")
    public Result add(@RequestBody Policy policy){
        Boolean flag = policyService.save(policy);
        return flag ? Result.success("添加新闻政策成功") : Result.error("添加新闻政策失败");
    }

    @GetMapping("/delete/{policyId}")
    @Operation(summary = "删除新闻政策")
    public Result delete(@PathVariable Integer policyId){
        Boolean flag = policyService.removeById(policyId);
        return flag ? Result.success("删除新闻政策成功") : Result.error("不存在该新闻政策Id");
    }

    @PutMapping("/update")
    @Operation(summary = "修改新闻政策")
    public Result update(@RequestBody Policy policy){
        Boolean flag = policyService.updateById(policy);
        return flag ? Result.success("修改新闻政策成功") : Result.error("修改新闻政策失败");
    }

    @GetMapping("/selectByPage/{current}/{size}")
    @Operation(summary = "分页查询新闻政策")
    public Result selectByPage(@PathVariable Integer current, @PathVariable Integer size){
        IPage<Policy> page = policyService.page(new Page<>(current,size));
        return Result.success(page);
    }

    @PostMapping("/selectByCondition")
    @Operation(summary = "根据标题、政策Id、日期(年月日)条件查询新闻政策")
    public Result selectByCondition(@RequestBody PolicyQuery policyQuery){
        LambdaQueryWrapper<Policy> lqw = new LambdaQueryWrapper<>();
        lqw.like(policyQuery.getPolicyTitle()!=null&&!policyQuery.getPolicyTitle().equals(""),
                        Policy::getPolicyTitle,policyQuery.getPolicyTitle())
                .eq(policyQuery.getPolicyId()!=null,Policy::getPolicyId,policyQuery.getPolicyId());
        // 获取今天的开始时间和结束时间
        if(policyQuery.getPolicyDate()!=null){
            LocalDateTime startOfDay = LocalDateTime.of(policyQuery.getPolicyDate(), LocalTime.MIN);
            LocalDateTime endOfDay = LocalDateTime.of(policyQuery.getPolicyDate(), LocalTime.MAX);
            lqw.ge(Policy::getCreateTime, startOfDay).le(Policy::getCreateTime, endOfDay);
        }

        IPage<Policy> page = policyService.page(new Page<>(policyQuery.getCurrent(), policyQuery.getSize()),
                lqw);
        return Result.success(page);
    }
}

